package com.luyuan.crm.sms.task.support;

import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.springframework.core.task.TaskExecutor;

import com.luyuan.crm.sms.Constant;
import com.luyuan.crm.sms.command.BaseCommand;
import com.luyuan.crm.sms.task.CommandExecutor;
import com.luyuan.crm.sms.task.SmsTaskListener;

/*******************************
 * 2012-7-18
 * Description:
 * </p>
 * <p>
 * Copyright: Copyright (c) 2012
 * </p>
 * 
 * @author chenqibo
 * @version 1.0
 ********************************/

@SuppressWarnings("rawtypes")
public class CommandExecutorImpl implements CommandExecutor {

    private Client client = null;

    private TaskExecutor taskExecutor;

    @Override
    public void execute(final BaseCommand command, SmsTaskListener listener) {
        this.taskExecutor.execute(new SmsCommandTask(command, listener));
    }

    private class SmsCommandTask implements Runnable {

        private BaseCommand command;

        private SmsTaskListener listener;

        public SmsCommandTask(BaseCommand command, SmsTaskListener listener) {
            this.command = command;
            this.listener = listener;
        }

        @Override
        public void run() {
            if (client == null) {
                synchronized (Constant.SMS_NET_URL) {
                    if (client == null) {
                        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
                        client = dcf.createClient(Constant.SMS_NET_URL);
                    }
                }
            }

            try {
                Object[] objects = client.invoke(command.getOperateName(), command.getParams());
                listener.onSuccess(objects);
            } catch (Exception e) {
                listener.onError(e);
            }
        }
    }

    public void setTaskExecutor(TaskExecutor taskExecutor) {
        this.taskExecutor = taskExecutor;
    }
}
